<?php
namespace app\admin\controller;

use app\common\model\Article as M_Article;
use app\common\model\Images as M_Images;
use app\common\validate\Article as V_Article;
use bigDream\thinkJump\Jump;
use think\facade\Filesystem;
use think\facade\Request;

/**
 * 文章管理
 * @package app\admin\controller
 * @author jwj <jwjbjg@gmail.com>
 * @copyright jwj
 */
class Article
{
    /**
     * 列表
     * @return \think\response\Json|\think\response\View
     */
    public function index()
    {
        if (Request::isGet()) {
            return view();
        }

        $query = M_Article::autoSearch()
            ->with(['category'])
            ->withoutField(['content'])
            ->order('update_time', 'desc')
            ->append(['status_text', 'url']);

        $result = $query->paginate(Request::param('limit', 20));

        return json([
            'code'  => 0,
            'msg'   => '获取成功',
            'count' => $result->total(),
            'data'  => $result->items()
        ]);
    }

    /**
     * 添加
     * @return \think\response\View
     */
    public function add()
    {
        if (!Request::isAjax()) {
            return view('edit', ['result' => '{}']);
        }

        $validate = (new V_Article())->scene('add');
        $data = Request::only($validate->getSceneField());
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        M_Article::startTrans();
        try {
            $result = M_Article::create($data);

            M_Article::commit();
        } catch (\Exception $e) {
            M_Article::rollback();

            Jump::error('发生错误:' . $e->getMessage());
        }

        Jump::success('添加成功');
    }

    /**
     * 编辑
     * @return \think\response\View
     */
    public function edit()
    {
        $result = M_Article::where('id', Request::param('id'))->find();
        if (null === $result) {
            Jump::error('内容不存在');
        }

        if (!Request::isAjax()) {
            return view('', [
                'result' => $result,
            ]);
        }

        $validate = (new V_Article())->scene('edit');
        $data = Request::only($validate->getSceneField());
        if (!$validate->check($data)) {
            Jump::error($validate->getError());
        }

        M_Article::startTrans();
        try {
            $result->save($data);

            M_Article::commit();
        } catch (\Exception $e) {
            M_Article::rollback();

            Jump::error('发生错误:' . $e->getMessage());
        }

        Jump::success('修改成功');
    }

    /**
     * 删除
     */
    public function delete()
    {
        M_Article::startTrans();
        try {
            $result = M_Article::where('id', 'in', Request::param('id'))->where('id', '<>', 1)->delete();

            M_Article::commit();
        } catch (\Exception $e) {
            M_Article::rollback();

            Jump::error($e->getMessage());
        }

        Jump::success('删除成功');
    }

    /**
     * 文件上传
     * @return \think\response\Json
     */
    public function upload()
    {
        try {
            $file = Request::file('editormd-image-file');
            if (null === $file) {
                throw new \Exception('请上传文件', UPLOAD_ERR_NO_FILE);
            }

            validate(['file' => [
                'fileSize' => 4 * 1024 * 1024,
                'fileExt'  => 'gif,jpg,jpeg,png,bmp,webp'
            ]])->check(['file' => $file]);
        } catch (\Exception $e) {
            return json([
                'success' => 0,
                'message' => $e->getMessage(),
            ]);
        }

        $rule = 'md5';
        $hash = $file->hash($rule);
        $images = M_Images::where('hash', $hash)->find();
        if (null === $images) {
            $path = 'article';
            $path = Filesystem::disk('public')->putFile($path, $file, $rule);
            $url = Filesystem::getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);

            $images = M_Images::create([
                'user_id' => app('Administrator')['id'],
                'url'     => $url,
                'size'    => $file->getSize(),
                'name'    => $file->getOriginalName(),
                'mime'    => $file->getMime(),
                'hash'    => $hash,
            ]);
        }

        return json([
            'success' => 1,
            'message' => '上传成功',
            'url'     => $images['url'],
            'data'    => $images,
        ]);
    }
}
